#  文本检测模块
# 文本检测模块通常会输出文本区域的边界框（Bounding Boxes），这些边界框将作为输入传递给文本识别模块进行后续处理。

# 导入统一配置并初始化环境变量
from app.utils.logger import get_logger, timing_decorator

# 模块级logger，用于类内部使用
logger = get_logger(__name__)
import logging
from pathlib import Path
import os

# 设置多个环境变量来控制PaddlePaddle的日志输出
# os.environ['GLOG_v'] = '0'
# os.environ['GLOG_logtostderr'] = '0'
# os.environ['GLOG_minloglevel'] = '2'  # 0=INFO, 1=WARNING, 2=ERROR, 3=FATAL
# os.environ['PADDLE_LOG_LEVEL'] = 'WARNING'
# os.environ['FLAGS_print_debug_info'] = 'false'
# os.environ['FLAGS_enable_paddle_debug'] = 'false'
# # 启用调试信息
# os.environ["PADDLE_PDX_DEBUG"] = "False"
# # 禁用预先初始化模型对象和下载模型
# os.environ["PADDLE_PDX_EAGER_INIT"] = "True"
# print(os.getenv("PADDLE_PDX_CACHE_HOME"))

# print(f"输出日志Name：{logging.Logger.manager.loggerDict.keys()}")
# # 设置根日志记录器级别
# logging.basicConfig(
#     level=logging.DEBUG,
#     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
#     handlers=[
#         logging.StreamHandler()  # 输出到控制台
#     ]
# )
#
# # 获取并配置不同库的日志记录器
# loggers_set_info = [
#     'paddlex',
#     'paddleocr',
#     'paddle',
#     'urllib3',
# ]
#
# for logger_name in loggers_set_info:
#     logger = logging.getLogger(logger_name)
#     logger.setLevel(logging.INFO)  # 设置为INFO级别，避免DEBUG信息
#     if not logger.handlers:
#         console_handler = logging.StreamHandler()
#         console_handler.setLevel(logging.INFO)
#         formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#         console_handler.setFormatter(formatter)
#         logger.addHandler(console_handler)
#     logger.propagate = False  # 防止日志向上传播
#
# # 将可能产生详细日志的库设置为WARNING级别
# noisy_loggers = [
#     # 'paddle.fluid',
#     # 'paddle.inference',
#     # 'paddle.distributed',
#     # 'paddle.optimizer',
#     # 'paddle.nn',
#     # 'paddle.static',
#     # 'ppdet',
#     # 'ppocr',
# ]
#
# for logger_name in noisy_loggers:
#     logging.getLogger(logger_name).setLevel(logging.WARNING)

# 将所有其他库的日志级别设置为WARNING，避免DEBUG信息
# for name in logging.Logger.manager.loggerDict.keys():
#     logger = logging.getLogger(name)
#     if logger.level == logging.NOTSET:
#         logger.setLevel(logging.debug)
#
# print(f"输出日志Name+++：{logging.Logger.manager.loggerDict.keys()}")

TEST_DATA_DIR = Path(__file__).parent / "test_files"
SUB_DIR = TEST_DATA_DIR / "1715339805571"

from paddleocr import PaddleOCR, TextDetection
import json


@timing_decorator(logger)
def text_recognition_demo(image_path):
    logger.info("使用 TextDetection 检测文本")
    recognizer = TextDetection(
        model_name="PP-OCRv5_server_det",  # 可选，使用默认模型
    )
    results = recognizer.predict(input=image_path)

    for result in results:
        logger.info("识别结果:")
        result.print()

        # # 保存结果到图像
        # result.save_to_img(save_path="./output/")
        #
        # # 保存结果到JSON文件
        # result.save_to_json(save_path="./output/recognition_result.json")

        # 直接访问识别文本和置信度
        # print(f"识别文本: {result.text}")
        # print(f"置信度: {result.score}")


@timing_decorator(logger)
def text_recognition_with_character_coordinates(image_path):
    """
    使用PaddleOCR进行文本识别并获取字符级坐标信息
    """
    print("使用PaddleOCR进行文本识别并获取字符级坐标信息")
    # 创建PaddleOCR实例，启用字符级坐标返回
    ocr = PaddleOCR(
        text_recognition_model_name="PP-OCRv5_server_rec",
        text_detection_model_name="PP-OCRv5_server_det",
        use_textline_orientation=False,
        use_doc_orientation_classify=False,  # 禁用文档预处理
        use_doc_unwarping=False,  # 禁用文档矫正
        return_word_box=True  # 返回单词/字符坐标
    )

    # 执行OCR识别
    results = ocr.predict(input=image_path)

    # 处理结果
    for result in results:
        # 打印完整结果
        # 获取JSON数据并手动格式化
        # formatted_json = json.dumps(result.json, indent=2, ensure_ascii=False)
        # print(formatted_json)

        # 通过字典方式访问属性（根据日志输出分析）
        res_data = result.json['res']
        # print(f"检测到的文本框坐标: {res_data['dt_polys']}")
        # print(f"识别文本: {res_data['rec_texts']}")
        # print(f"置信度: {res_data['rec_scores']}")
        # print(f"文本类型: {res_data['text_type']}")

        # 如果启用了return_word_box，获取字符级坐标
        if 'text_word_boxes' in res_data and 'text_word' in res_data:
            print("字符级坐标:")
            for i, (word_boxes, words) in enumerate(zip(res_data['text_word_boxes'], res_data['text_word'])):
                print(f"  文本行 {i}:")
                for j, (box, char) in enumerate(zip(word_boxes, words)):
                    print(f"    字符 '{char}' 坐标: {box}")
    format_ocr_results_as_json(results)


def format_ocr_results_as_json(results):
    """
    将PaddleOCR的识别结果格式化为JSON数据
    """
    # 按指定格式处理结果
    for result in results:
        res_data = result.json['res']

        # 处理每个检测到的文本框
        dt_polys = res_data.get('dt_polys', [])
        rec_texts = res_data.get('rec_texts', [])
        rec_scores = res_data.get('rec_scores', [])

        # 确保三个列表长度一致
        min_length = min(len(dt_polys), len(rec_texts), len(rec_scores))

        for i in range(min_length):
            # 构造符合要求的JSON格式
            formatted_result = {
                "text": rec_texts[i],
                "bbox": dt_polys[i],
                "score": rec_scores[i]
            }

            # 输出格式化的JSON字符串
            print(json.dumps(formatted_result, ensure_ascii=False))


if __name__ == "__main__":
    image_path = str(SUB_DIR / "1715339805571_002.jpg")

    text_recognition_demo(image_path)

    text_recognition_with_character_coordinates(image_path)
